package com.masterclient.app.modules.goods.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.status.StatusBarUtils;
import com.eoner.baselibrary.bean.goods.CommodityDetailData;
import com.eoner.baselibrary.bean.goods.SellerMessage;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.MainViewHolder;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.modules.cart.beans.AddShopCartBean;
import com.masterclient.app.modules.goods.adapter.CommodityDetailBannerAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailDescriptionAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailFootAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailInformationAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailSellerAdapter;
import com.masterclient.app.modules.goods.contract.CommodityDetailContract;
import com.masterclient.app.modules.goods.contract.CommodityDetailPresenter;
import com.masterclient.app.modules.goods.widget.SkuSelectDialog;
import com.masterclient.app.utils.CommonUtil;
import com.gyf.immersionbar.ImmersionBar;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;

@Route(path = AroutePath.MATERIAL_DETAIL_ACTIVITY)
public class MaterialDetailActivity extends BaseActivity<CommodityDetailPresenter> implements CommodityDetailContract.View {

    @BindView(R.id.root)
    View root;
    @BindView(R.id.title_layout)
    View title_layout;
    @BindView(R.id.iv_back_top)
    View iv_back_top;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_title)
    TextView tv_title;

    //底部购物车和客服
    @BindView(R.id.ll_bottom)
    View ll_bottom;

    @Autowired(name = "id")
    String id;

    //埋点
    @Autowired(name = "anchor_id")
    String anchor_id;
    @Autowired(name = "button_name")
    String button_name;
    @Autowired(name = "isAnalytics")
    boolean isAnalytics;


    @Autowired(name = "product_sourcepage")
    String product_sourcepage;
    @Autowired(name = "source_page_id")
    String sourcePageId;
    @Autowired(name = "source_page")
    String sourcePage;
    @Autowired(name = "source_module")
    String sourceModule;
    @Autowired(name = "source_element")
    String sourceElement;
    @Autowired(name = "source_position")
    String sourcePosition;
    @Autowired(name = "ad_id")
    String ad_id;
    @Autowired(name = "ad_name")
    String ad_name;
    @Autowired(name = "key_word")
    String key_word;
    @Autowired(name = "key_word_type")
    String key_word_type;
    @Autowired(name = "isFromLive")
    boolean isFromLive;

    final List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    DelegateAdapter delegateAdapter;
    CommodityDetailBannerAdapter adapter_banner;
    CommodityDetailInformationAdapter adapter_information;
    CommodityDetailSellerAdapter adapter_seller;
    CommodityDetailDescriptionAdapter adapter_description;
    CommodityDetailFootAdapter adapter_foot;
    RxBus rxBus;
    String buy_type = "2";
    JSONObject buy_product;
    private boolean isCountDown;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.material_detail_activity);
        EventBusManager.register(this);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        StatusBarUtils.immersive(getActivity());
        StatusBarUtils.setPaddingSmart(mContext, title_layout);

        status_bar_height = ImmersionBar.getStatusBarHeight(getActivity());
        title_layout.setAlpha(0);
        init();
        add_listener();
        mPresenter.getCommodityDetail(id, "",false);
    }

    private void init() {
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(mContext);
        layoutManager.setInitialPrefetchItemCount(10);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemViewCacheSize(16);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recyclerView.setRecycledViewPool(viewPool);
        for (int i = 0; i < 13; i++) {
            viewPool.setMaxRecycledViews(i, 10);
        }
        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);

        rxBus = RxBus.$();
        UserDataManager.getInstance().requestCustomerInfo(null);
    }

    //TODO:通知登录成功
    /**
     * 登录成功刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        UserDataManager.getInstance().requestCustomerInfo(null);
        mPresenter.getCommodityDetail(id, "",false);
    }


    int distanceY;
    int status_bar_height = 0;
    float search_layout_height = dp2px(44) + status_bar_height;

    private void add_listener() {

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                distanceY += dy;
                VirtualLayoutManager lm = (VirtualLayoutManager) recyclerView.getLayoutManager();
                int first = 0, last = 0, total = 0;
                first = ((LinearLayoutManager) lm).findFirstVisibleItemPosition();
                last = ((LinearLayoutManager) lm).findLastVisibleItemPosition();
                total = recyclerView.getAdapter().getItemCount();
                //System.out.println(first + " ------- > " + last + " ------- > " + total);
                int scrollY = 0;
                SparseIntArray mRecyclerItemHeight = new SparseIntArray();
                View c = recyclerView.getLayoutManager().getChildAt(0); //this is the first visible row
                if (c != null) {
                    scrollY = -c.getTop();
                    mRecyclerItemHeight.put(first, c.getHeight());
                    for (int i = 0; i < first; ++i) {
                        scrollY += mRecyclerItemHeight.get(i); //add all heights of the views that are gone
                    }
                }
                int alpha = (int) (Math.abs(scrollY) / search_layout_height * 255);
                if (alpha > 255) {
                    alpha = 255;
                } else if (alpha < 0) {
                    alpha = 0;
                }
                if (first != 0) {
                    alpha = 255;
                }

                String hexString = Integer.toHexString(alpha);
                if (hexString.length() < 2) {
                    hexString += "0";
                }
                if (alpha > 0) {
                    //StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#" + hexString + "FFFFFF"));
                    iv_back.setImageResource(R.mipmap.goods_detail_back_icon0);
                    tv_title.setVisibility(View.VISIBLE);
                } else {
                    //StatusBarUtil.transparencyBar(getActivity());
                    iv_back.setImageResource(R.mipmap.goods_detail_back_icon);
                    tv_title.setVisibility(View.GONE);
                }
                title_layout.setBackgroundColor(Color.parseColor("#" + hexString + "FFFFFF"));
                title_layout.setAlpha(alpha == 0 ? 1 : alpha);

                //System.out.println(first + "scrollY ------- > " + scrollY);
                if (first > detail_index - 1) {
                    iv_back_top.setVisibility(View.VISIBLE);
                } else {
                    iv_back_top.setVisibility(View.GONE);
                }
                if (comment_index == 0) {
                    comment_index = detail_index;
                }
            }
        });

    }

    @OnClick({R.id.iv_back_layout, R.id.iv_back_top, R.id.tv_relevance_goods})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_layout:
                finish();
                break;
            case R.id.iv_back_top:
                distanceY = 0;
                recyclerView.scrollToPosition(0);
                break;
            case R.id.tv_relevance_goods:
                //TODO 点击关联商品操作
                setResult(RESULT_OK);
                finish();
                break;
        }
    }

    SkuSelectDialog skuSelectDialog;
    String max_discount_coupon_id = "0";

    private void show_sku_select_dialog() {
        if (data == null) {
            showToast("商品不存在");
            return;
        }

        if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
            startActivitry(QuickLoginActivity.class, new String[][]{{"intentSource", "商品详情"}});
            return;
        }


        skuSelectDialog = new SkuSelectDialog(MaterialDetailActivity.this, data, 1);

        skuSelectDialog.setSkuSelectCallBack((product_id, skuName, num, operate, max_discount_coupon_id, couponId, couponName) -> {
            if (operate == 0) {
                show_progressDialog();
                mPresenter.addCart(product_id, num);
            } else if (operate == 1) {

                MaterialDetailActivity.this.max_discount_coupon_id = max_discount_coupon_id;
                buy_product = new JSONObject();
                try {
                    buy_product.put(product_id, Integer.valueOf(num));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!"0".equals(max_discount_coupon_id)) {
                    //调用领券接口
                    show_progressDialog();
                    mPresenter.pickUpSalesrule(max_discount_coupon_id, id);
                } else {
                    if (!isCountDown) {
                        show_progressDialog();
                        mPresenter.confirm_order(buy_product.toString(), buy_type, data.getSale_type());
                    }
                }
            }
        });

        skuSelectDialog.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusManager.unRegister(this);
        if (adapter_banner != null) {
            adapter_banner.destroy();
        }
    }

    int index = 0;
    int comment_index, detail_index;
    CommodityDetailData data;

    @Override
    public void showCommodityDetail(CommodityDetailData data) {

        if (!TextUtils.isEmpty(data.getVip_level())) {
            UserDataManager.getInstance().updateUserLevel(data.getVip_level());
        }

        this.data = data;
        adapters.clear();
        delegateAdapter.setAdapters(adapters);
        recyclerView.setAdapter(delegateAdapter);
        index = 0;

        //banner区
        List<String> banner_images = data.getImages();
        if (adapters.contains(adapter_banner)) {
            adapters.remove(adapter_banner);
        }
        if (banner_images != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_banner = new CommodityDetailBannerAdapter(MaterialDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_banner, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_banner);
            index++;
        }

        //商品基础信息区域
        if (adapters.contains(adapter_information)) {
            adapters.remove(adapter_information);
        }
        boolean hasInformation = true;
        if (hasInformation) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_information = new CommodityDetailInformationAdapter(MaterialDetailActivity.this, layoutHelper, 1, null, data,false) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_information, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_information.setOnInformationCallback(new CommodityDetailInformationAdapter.OnInformationCallback() {
                @Override
                public void favoriteClick() {

                    if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                        startActivitry(QuickLoginActivity.class, new String[][]{{"intentSource", "商品详情"}});
                    } else {
                        if (data.isIs_favorite()) {
                            mPresenter.removeFavorite(data.getProduct_id());
                        } else {
                            mPresenter.addFavorite(data.getProduct_id());
                        }
                    }
                }

                @Override
                public void upgradeClick() {
                    show_sku_select_dialog();
                }
            });
            adapters.add(adapter_information);
            //commodity_index = index;
            index++;
        }

        //店铺
        if (adapters.contains(adapter_seller)) {
            adapters.remove(adapter_seller);
        }
        SellerMessage sellerMessage = data.getSeller();
        if (sellerMessage != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_seller = new CommodityDetailSellerAdapter(MaterialDetailActivity.this, layoutHelper, 1, null, data,false) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_seller, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_seller);
            index++;
        }

        //详情
        if (adapters.contains(adapter_description)) {
            adapters.remove(adapter_description);
        }
        boolean hasDescription = true;
        if (hasDescription) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_description = new CommodityDetailDescriptionAdapter(MaterialDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_description, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_description);
            detail_index = index;
            index++;
        }

        //底部
        boolean hasFoot = true;
        if (adapters.contains(adapter_foot)) {
            adapters.remove(adapter_foot);
        }
        if (hasFoot) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_foot = new CommodityDetailFootAdapter(MaterialDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_foot, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_foot);
            index++;
        }

        delegateAdapter.setAdapters(adapters);

        //底部按钮展示
        display_bottom_btn();
    }

    private void display_bottom_btn() {
        ll_bottom.setVisibility(View.VISIBLE);
    }

    @Override
    public void getCommodityDetailFailed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void pickUpSalesruleSuccess(String coupon_code, String msg) {
        dismiss_progressDialog();
        showToast(msg);
        receive_coupon_result_next();
    }

    @Override
    public void pickUpSalesruleFailed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
        receive_coupon_result_next();
    }

    private void receive_coupon_result_next() {
        if (!"0".equals(max_discount_coupon_id) && !isCountDown) {
            max_discount_coupon_id = "0";
            mPresenter.confirm_order(buy_product.toString(), buy_type, data.getSale_type());
        }
    }

    @Override
    public void favoriteFailed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void removeFavoriteSuccess() {
        dismiss_progressDialog();
        showToast("移除收藏成功");
        data.setIs_favorite(!data.isIs_favorite());
        adapter_information.notifyDataSetChanged();
    }

    @Override
    public void addFavoriteSuccess() {
        dismiss_progressDialog();
        showToast("收藏成功");
        data.setIs_favorite(!data.isIs_favorite());
        adapter_information.notifyDataSetChanged();
    }

    @Override
    public void addCartSuccess(AddShopCartBean addShopCartBean) {
        dismiss_progressDialog();
        showToast("加入购物车成功");
    }

    @Override
    public void addCartFailed(String msg) {
        showToast(msg);
        dismiss_progressDialog();
    }

    @Override
    public void confirm_order_success(ConfirmOrderData data, String code) {
        dismiss_progressDialog();
        Toast tst = Toast.makeText(this, "", Toast.LENGTH_LONG);
        if (code.equals("20001")) {
            isCountDown = true;
            Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.computation())
                    .take(4).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(Long aLong) {
                    tst.setText(data.getText() + (3 - aLong) + "s");
                    tst.show();
                }

                @Override
                public void onError(Throwable e) {
                    isCountDown = false;
                }

                @Override
                public void onComplete() {
                    isCountDown = false;
                    if (!TextUtils.isEmpty(data.getUrl())) {
                        CommonUtil.goAnyWhere(MaterialDetailActivity.this,  data.getUrl(), "", "", "", "");
                    }
                }
            });
        } else {
            ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY)
                    .withString("convert", this.data.getProduct_type())
                    .withString("buy_type", "2")
                    .withString("live_room_id", this.data.getProduct_live() == null ? "0" : this.data.getProduct_live().getLiveRoomId())
                    .withString("buy_product", buy_product.toString())
                    .withSerializable("confirm_order_data", data).navigation();
        }
    }

    @Override
    public void confirm_order_failed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void setSaleRemainSuccess() {

    }

    @Override
    public void setSaleRemainFail(String s) {

    }
}
